<template>
  <div class="dashboard-statistics">
    <!-- 经营数据 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6" v-for="item in summaryList" :key="item.title">
        <el-card :body-style="{ padding: '24px' }" class="summary-card" :style="{ background: item.bg }">
          <div class="summary-title">{{ item.title }}</div>
          <div class="summary-value">{{ item.value }}</div>
          <div class="summary-icon"><el-icon :size="36"><component :is="item.icon" /></el-icon></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb20">
      <!-- 订单统计 -->
      <el-col :span="8">
        <el-card>
          <template #header>订单统计</template>
          <div ref="orderPie" style="height:220px;"></div>
        </el-card>
      </el-col>
      <!-- 数据任务统计 -->
      <el-col :span="8">
        <el-card>
          <template #header>数据任务统计</template>
          <div ref="taskPie" style="height:220px;"></div>
        </el-card>
      </el-col>
      <!-- 用户概况 -->
      <el-col :span="8">
        <el-card>
          <template #header>用户概况</template>
          <el-row>
            <el-col :span="24" v-for="item in userSummary" :key="item.title" class="user-summary">
              <div>{{ item.title }}</div>
              <div class="user-value">{{ item.value }}</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 注册用户分析 -->
    <el-card>
      <template #header>注册用户分析</template>
      <div ref="userBar" style="height:300px;"></div>
    </el-card>
  </div>
</template>

<script setup name="Index">
const version = ref('3.6.6')

function goTarget(url) {
  window.open(url, '__blank')
}

import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { Money, Tickets, User, UserFilled } from '@element-plus/icons-vue'

const summaryList = ref([
  { title: '今日订单总额（元）', value: '1000.00', icon: Money, bg: '#2ecc71' },
  { title: '今日订单总数', value: '100', icon: Tickets, bg: '#9b59b6' },
  { title: '今日新增用户数', value: '265.66', icon: User, bg: '#3498db' },
  { title: '今日新增商户', value: '265', icon: UserFilled, bg: '#f39c12' }
])

const userSummary = ref([
  { title: '商户数', value: 100 },
  { title: '新增用户数', value: 50 },
  { title: '累计用户数', value: 1000 }
])

const orderPieData = ref([
  { value: 335, name: '维修类' },
  { value: 310, name: '洗车类' },
  { value: 234, name: '保养类' }
])
const taskPieData = ref([
  { value: 100, name: '待处理', itemStyle: { color: '#e74c3c' } },
  { value: 400, name: '已处理', itemStyle: { color: '#1abc9c' } }
])
const userBarData = ref([120, 200, 150, 80, 70, 110, 130, 90, 160, 140, 100, 120, 130, 90, 110, 210, 180, 170, 190, 200, 220, 140, 130, 160, 150, 120, 110, 100, 90, 230])

const orderPie = ref(null)
const taskPie = ref(null)
const userBar = ref(null)

let orderPieChart = null
let taskPieChart = null
let userBarChart = null
let ws = null

onMounted(() => {
  orderPieChart = echarts.init(orderPie.value)
  taskPieChart = echarts.init(taskPie.value)
  userBarChart = echarts.init(userBar.value)
  setOrderPieOption()
  setTaskPieOption()
  setUserBarOption()
  connectWebSocket()
})

function setOrderPieOption() {
  orderPieChart.setOption({
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'right', data: orderPieData.value.map(i => i.name) },
    series: [{
      name: '订单类型',
      type: 'pie',
      radius: '60%',
      data: orderPieData.value
    }]
  })
}
function setTaskPieOption() {
  taskPieChart.setOption({
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'right', data: taskPieData.value.map(i => i.name) },
    series: [{
      name: '任务状态',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      data: taskPieData.value
    }]
  })
}
function setUserBarOption() {
  userBarChart.setOption({
    tooltip: {},
    xAxis: { type: 'category', data: Array.from({ length: 30 }, (_, i) => `${i + 1}号`) },
    yAxis: { type: 'value', name: '注册用户分析' },
    series: [{
      data: userBarData.value,
      type: 'bar',
      itemStyle: { color: '#409EFF' }
    }]
  })
}

// 监听数据变化自动刷新图表
watch(orderPieData, setOrderPieOption, { deep: true })
watch(taskPieData, setTaskPieOption, { deep: true })
watch(userBarData, setUserBarOption, { deep: true })

// WebSocket 实时更新，只处理后端实际推送的字段
function connectWebSocket() {
  ws = new WebSocket('ws://localhost:9502/ws/statistics') // 修改为你的后端ws地址
  ws.onopen = () => {
    console.log('WebSocket已连接')
  }
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      if (data.orderPie) orderPieData.value = data.orderPie
      console.log(data.orderPie)
      if (data.taskPie) taskPieData.value = data.taskPie
      console.log(data.taskPie)
      if (data.userSummary) userSummary.value = data.userSummary
      console.log(data.userSummary)
      if(data.summaryList) {
        data.summaryList.forEach((newItem, index) => {
          if (summaryList.value[index]) {
            summaryList.value[index].value = newItem.value.toString();
          }
        });
      }
      console.log(data.summaryList)
      // summaryList 和 userBarData 不做处理，保持默认
    } catch (e) {
      console.error('WebSocket数据解析失败', e)
    }
  }
  ws.onclose = () => {
    console.log('WebSocket已断开，3秒后重连')
    setTimeout(connectWebSocket, 3000)
  }
  ws.onerror = (e) => {
    console.error('WebSocket错误', e)
    ws.close()
  }
}
</script>

<style scoped>
.dashboard-statistics { padding: 20px; }
.mb20 { margin-bottom: 20px; }
.summary-card { color: #fff; position: relative; min-height: 120px; }
.summary-title { font-size: 16px; margin-bottom: 10px; }
.summary-value { font-size: 28px; font-weight: bold; }
.summary-icon { position: absolute; right: 24px; bottom: 24px; font-size: 36px; opacity: 0.2; }
.user-summary { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.user-value { font-size: 22px; font-weight: bold; height: 63px; display: flex; align-items: center }
</style>

